"""
Copyright (c) 2022 Guangdong University of Technology
PhotLab is licensed under [Open Source License].
You can use this software according to the terms and conditions of the [Open Source License].
You may obtain a copy of [Open Source License] at: [https://open.source.license/]

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.

See the [Open Source License] for more details.

Author: Meng Xiang, Junjiang Xiang
Created: 2023/8/19
Supported by: National Key Research and Development Program of China
"""

import numpy as np


def Gram_Schmidt_Orthogonalization(Iutput_I, Iutput_Q):
    length_min = min(len(Iutput_I), len(Iutput_Q))

    Average_Power_I = np.mean(Iutput_I ** 2)
    Correction_Coefficient = np.mean(Iutput_I * Iutput_Q)
    Refference = Iutput_Q - (Correction_Coefficient / Average_Power_I) * Iutput_I
    Average_power_Q = np.mean(Refference ** 2)
    Output_Q = Refference / np.sqrt(Average_power_Q)
    Output_I = Iutput_I / np.sqrt(Average_Power_I)

    return Output_I, Output_Q


def iq_compensation(input):
    """GSOP
            Args:
                input[0]: 输入X偏振I路, numpy类型
                input[1]: 输入X偏振Q路, numpy类型
                input[2]: 输入Y偏振I路, numpy类型
                input[3]: 输入Y偏振Q路, numpy类型

            Returns:
                output[0]: 输出X偏振信号
                output[1]: 输出Y偏振信号
            """
    ADC_X_I = np.real(input[0])
    ADC_X_Q = np.imag(input[0])
    ADC_Y_I = np.real(input[1])
    ADC_Y_Q = np.imag(input[1])

    rx_xi_tem, rx_xq_tem = Gram_Schmidt_Orthogonalization(ADC_X_I, ADC_X_Q)
    rx_yi_tem, rx_yq_tem = Gram_Schmidt_Orthogonalization(ADC_Y_I, ADC_Y_Q)
    Re_X = rx_xi_tem + 1j * rx_xq_tem
    Re_Y = rx_yi_tem + 1j * rx_yq_tem

    Re_X = np.expand_dims(Re_X, axis=1)
    Re_Y = np.expand_dims(Re_Y, axis=1)

    output = [Re_X, Re_Y]

    return output
